package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author junyong
 * @since 2024-8-3
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.不符合，返回错误信息
            return Result.fail("手机号格式错误!");
        }
        // 3.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 4.保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 5.发送验证码
        log.debug("发送验证码成功,验证码:{}", code);
        // 6.返回
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机格式不正确!");
        }
        // 2.校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.equals(code)) {
            // 3.不一致，报错
            return Result.fail("验证码错误!");
        }
        // 4.一致，根据手机号查询用户
        User user = query().eq("phone", phone).one();
        // 5.查不到，新用户。创建新用户，保存用户到数据库
        if (user == null) {
            user = createUserWithPhone(phone);
        }
        // 6.保存用户到redis
        // 6.1生成Token
        String token = UUID.randomUUID().toString(true);
        // 6.2拿到UserDTO
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // 6.3将UserDTO对象转为Hash结构
        Map<String, Object> map = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setFieldValueEditor((fieldName, fieldValue) ->
                        fieldValue.toString()));
        // 6.4保存hash数据到redis
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, map);
        // 6.5设置token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.SECONDS);
        // 7.返回Token
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 3.当前年月
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 4.拿到今天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.存入Redis
        String key = USER_SIGN_KEY + userId + date;
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 3.当前年月
        String date = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 4.拿到今天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.拿到到今天为止的所有bit位
        String key = USER_SIGN_KEY + userId + date;
        List<Long> bits = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands
                        .create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0));
        if (bits == null || bits.size() == 0) {
            return Result.ok(0);
        }
        Long num = bits.get(0);
        if (num == null || num == 0) {
            return Result.ok(0);
        }
        int res = 0;
        while (num != 0) {
            if ((num & 1) == 1) {
                res++;
                num >>>= 1;//无符号右移
            } else {
                break;
            }
        }
        return Result.ok(res);
    }

    /**
     * 创建用户并保存到数据库
     *
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {
        // 1.创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        // 2.保存用户
        save(user);
        return user;
    }
}
